package com.ewzj.bigdata.mvp.presenter

import android.app.Application
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import com.ewzj.bigdata.app.config.AppKey
import com.ewzj.bigdata.app.utils.RxUtils
import com.ewzj.bigdata.mvp.contract.CitySelectorActivityContract
import com.ewzj.bigdata.mvp.model.bean.CitygroupBean
import com.ewzj.bigdata.mvp.model.reqbean.ReqCityBean
import com.ewzj.bigdata.mvp.model.reqbean.ReqSearchCityBean
import com.ewzj.bigdata.mvp.model.rspbean.BaseData
import com.ewzj.bigdata.mvp.model.rspbean.CityBean
import com.ewzj.bigdata.mvp.model.rspbean.CitySearchBean
import com.ewzj.bigdata.mvp.ui.adapter.CityAdapter
import com.ewzj.bigdata.mvp.ui.adapter.HotcityAdapter
import com.ewzj.bigdata.mvp.ui.view.ObservableRecyclerView
import com.google.gson.Gson
import com.jess.arms.mvp.BasePresenter
import com.jess.arms.utils.DataHelper
import com.jess.arms.utils.UiUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observables.GroupedObservable
import io.reactivex.schedulers.Schedulers
import me.jessyan.rxerrorhandler.core.RxErrorHandler
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber
import java.util.*
import javax.inject.Inject

/**
 * author:zhangjing
 * 作用:
 * return:
 */
class CitySelectorActivityPresenter @Inject constructor(val mGson: Gson, val mErrorHandler: RxErrorHandler, val application: Application, view: CitySelectorActivityContract.View, model: CitySelectorActivityContract.Model) : BasePresenter<CitySelectorActivityContract.Model, CitySelectorActivityContract.View>(model, view) {
    val hotdatas = ArrayList<CityBean.ListEntity>()
    var allcitydatas = ArrayList<CitygroupBean>()
    val hotAdapter = HotcityAdapter(hotdatas)
    val cityAdapter = CityAdapter(allcitydatas)
    private var searchtitle = ""
    val context by lazy { mRootView as AppCompatActivity }
    fun init() {
        if (AppKey.bdLocation == null || AppKey!!.bdLocation?.addrStr.isNullOrEmpty()) {
            mRootView.initLocationCity("定位失败")
        } else {
            mRootView.initLocationCity(AppKey!!.bdLocation!!.address.city)
        }
        mRootView.initCitylistview(cityAdapter)
        mRootView.initHotCityview(hotAdapter)
    }

    fun loadHotCitydata() {
        var req: ReqCityBean = ReqCityBean()
        req.is_hot = "1"
        mModel.loadCityfromNet(req).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(object : ErrorHandleSubscriber<BaseData<CityBean>>(mErrorHandler) {
                    override fun onNext(t: BaseData<CityBean>) {
                        hotAdapter.setNewData(t.data!!.list)
                    }

                })
    }

    fun loadAllCityData() {
        var req: ReqCityBean = ReqCityBean()
        req.is_group = "-1"
        mModel.loadCityfromCache(req).compose(RxUtils.applySchedulers(mRootView))
                .map { t -> t.list }
                .map { t -> Observable.fromIterable(t).groupBy { t ->
                            run {
                                if (t.first.isNullOrEmpty()) {
                                    t.first = "#"
                                }
                            }
                            t.first
                        }
                }.flatMap { t: Observable<GroupedObservable<String, CityBean.ListEntity>> -> t.take(1000) }
                .map { t ->
                    run {
                        val group = CitygroupBean(true, t.getKey())
                        var obser=t.toList()
                        obser.subscribe({ t1 ->
                            allcitydatas.add(group)
                                for (i in t1.indices) {
                                    allcitydatas.add(CitygroupBean(t1.get(i)))
                                }
                        })
                    }
                    allcitydatas
                }
                .subscribe(object :ErrorHandleSubscriber<List<CitygroupBean>>(mErrorHandler){
                    override fun onNext(t1: List<CitygroupBean>?) {
                       cityAdapter.setNewData(t1)
                    }

                })


    }
    fun searchData(word:String){
        if (word.isNullOrEmpty()){
            if (allcitydatas.size!=0){
                cityAdapter.setNewData(allcitydatas)
            }
            return
        }
        val reqSearchCityBean = ReqSearchCityBean(word)
        var searchgroups = ArrayList<CitygroupBean>()
        mModel.searchCity(reqSearchCityBean).compose(RxUtils.applySchedulers(mRootView))
                .map { t -> t.data!!.list }
                .map { t ->run{
                    for (i in t.indices) {
                        val city = t.get(i)
                        if (city.getPingyin() != null) {
                            val str = city.getPingyin()!![0] + ""
                            if (str != searchtitle) {
                                val group = CitygroupBean(true, str)
                                searchgroups.add(group)
                                searchtitle = str
                                val item = CityBean.ListEntity()
                                item.id = city.getId()
                                item.first = str
                                item.city = city.getCity()
                                searchgroups.add(CitygroupBean(item))
                            } else {
                                val item = CityBean.ListEntity()
                                item.id = city.getId()
                                item.first = str
                                item.city = city.getCity()
                                searchgroups.add(CitygroupBean(item))
                            }
                        } else {
                            val item = CityBean.ListEntity()
                            item.id = city.getId()
                            item.city = city.getCity()
                            searchgroups.add(CitygroupBean(item))
                        }
                    }}
                    searchgroups
                }.subscribe(object :ErrorHandleSubscriber<List<CitygroupBean>>(mErrorHandler){
            override fun onNext(t: List<CitygroupBean>) {
                cityAdapter.setNewData(t)
            }

        })
    }

    fun locationCityData(city:String){
        mModel.searchCity(ReqSearchCityBean(city)).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(object :ErrorHandleSubscriber<BaseData<CitySearchBean>>(mErrorHandler){
                    override fun onNext(t: BaseData<CitySearchBean>) {
                        if (t.data!!.list.size==0){
                            UiUtils.SnackbarText("该城市尚未开通")
                        }else{
                            val listEntity = t!!.data!!.list.get(0)
                            val cityBean = CityBean.ListEntity()
                            cityBean.city = listEntity.getCity()
                            cityBean.id = listEntity.getId()
                            cityBean.lon = listEntity.getLon()
                            cityBean.lat = listEntity.getLat()
                            cityBean.locatecity = city
                            DataHelper.SetStringSF(context,AppKey.LOCATION_CITY,mGson.toJson(cityBean))
                            context.finish()
                        }
                    }

                })
    }

    fun scrollToHead(index:String,recyclerView: RecyclerView){
        Observable.just(index)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(object : ErrorHandleSubscriber<String>(mErrorHandler) {
            override fun onNext(s: String) {
                if (cityAdapter != null) {
                    val citygroupBeens = cityAdapter.data
                    for (citygroupBean in citygroupBeens) {
                        if (!TextUtils.isEmpty(citygroupBean.header)) {
                            if (citygroupBean.header.equals(s.toLowerCase())) {
                                val pos = cityAdapter.data.indexOf(citygroupBean)
                                recyclerView.smoothScrollToPosition(pos)
                            }
                        }

                    }
                }
            }
        })
    }

}